package com.oauth2;


import com.entity.TokenEntity;
import com.entity.UserEntity;
import com.google.gson.Gson;
import com.service.TokenService;
import com.utils.HttpContextUtils;
import com.utils.R;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * oauth2过滤器
 *
 * @author Mark sunlightcs@gmail.com
 */
public class OAuth2Filter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        // 获取请求token
        String token = getRequestToken((HttpServletRequest) request);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return new OAuth2Token(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 支持跨域时，允许 OPTIONS 请求
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token = getRequestToken((HttpServletRequest) request);
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 设置跨域响应头
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());

        // 如果没有token，直接返回401
        if (StringUtils.isBlank(token)) {
            String json = new Gson().toJson(R.error(HttpStatus.SC_UNAUTHORIZED, "请先登录"));
            httpResponse.getWriter().print(json);
            return false;
        }

        // 如果存在token，则尝试执行登录逻辑
        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());

        try {
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());
            String json = new Gson().toJson(r);
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return false;
    }

    private String getRequestToken(HttpServletRequest httpRequest) {
        String token = httpRequest.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }
        return token;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        System.out.print("执行");
        // 获取 token 后，取出用户信息
        UserEntity tokenEntity = (UserEntity) subject.getPrincipal();

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        System.out.print(tokenEntity);
        httpRequest.getSession().setAttribute("userId", tokenEntity.getId());
        httpRequest.getSession().setAttribute("role", tokenEntity.getRole());
        String tablename = null;
        if (tokenEntity.getRole().equals("管理员") || tokenEntity.getRole().equals("财务管理")
        || tokenEntity.getRole().equals("厨房主管")){
            tablename = "users";
        }else {
            tablename = "yonghu";
        }
        httpRequest.getSession().setAttribute("tableName", tablename);
        httpRequest.getSession().setAttribute("username", tokenEntity.getUsername());

        // 继续后续处理
        return super.onLoginSuccess(token, subject, request, response);
    }
}
